<template>
  <div>
    <img :src="image" ref="image" class="img">
    <van-nav-bar
      left-text="取消"
      right-text="确认"
      class="toolbar"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    >
    </van-nav-bar>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css';
import Cropper from 'cropperjs';
export default {
  name: "UpdataPhoto",
  created() {},
  mounted() {
    const image=this.$refs.image
    this.cropper = new Cropper(image, {
        aspectRatio: 16 / 9,
        viewMode:1,
        background:false,
        crop: function (e) {
            // console.log(e.detail.x);
            // console.log(e.detail.y);
            // console.log(e.detail.width);
            // console.log(e.detail.height);
            // console.log(e.detail.rotate);
            // console.log(e.detail.scaleX);
            // console.log(e.detail.scaleY);
        }
    })
  },
  data() {
    return {
      image: window.URL.createObjectURL(this.file),
      cropper:null
    };
  },
  props: {
    file:{
      require:true
    }
  },
  methods: {
     getCroppedCanvas () {
      return new Promise(resolve => {
        this.cropper.getCroppedCanvas().toBlob((blob) => {
          resolve(blob)
        })
      })
    },
    async onConfirm(){
      // 如果要求Content-type是multipart/form-data 一定要提交FormData专门用于文件上传
      // const fd=new FormData()
      // fd.append('photo',this.file)
      // $emit('close')
      const file = await this.getCroppedCanvas()
      const fd = new FormData()
      fd.append('photo', file)
      this.$emit('updata-photo', window.URL.createObjectURL(file))
      this.$emit('close')
    }
  },
};
</script>

<style lang="less" scoped>
.toolbar{
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #000;
}
.img {
  display: block;

  /* This rule is very important, please don't ignore this */
  max-width: 100%;
}
</style>
